const {
	exec,
	execFile,
	fork,
	spawn,
} = require('child_process');
const path = require('path');
const fs = require('fs');
const xlsx = require('node-xlsx');
const Response = require('./Response')
const {
	getTime,
	getDate,
	getYearWeek,
} = require('../utils/dateUtils')
const {
	_UltDB,
	_WebDB,
	_webCrawlerMongo,
} = global

const getNum = (function() {
	let _num = 0
	return () => _num += 1
})()

module.exports = {

	/**
	 * 歌单列表
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	list: async function(params) {
		let {
			pn = 1,
				ps = 10,
		} = params
		let start = (pn - 1) * ps
		let expTaskCol = await _webCrawlerMongo.getCollection('exp_task')
		let total = await expTaskCol.count()
		let docs = await expTaskCol.find().sort({
			week: -1,
		}).skip(start).limit(ps).toArray()
		return new Response('000', '成功', {
			total,
			docs,
		})
	},

	createTask: async function(params) {
		let {
			ips,
			week,
			source = 'all',
			minItem = 5,
		} = params
		let sourceName = '全部'
		if (source == 'wy')
			sourceName = '网易'
		if (source == 'qq')
			sourceName = 'QQ'
		let expTaskCol = await _webCrawlerMongo.getCollection('exp_task')
		let task = await expTaskCol.findOne({
			week,
		})
		if (!task || !task._id)
			return new Response('001', '生成Excel失败!')

		let exp_task_id = `${week}_${source}_min_${minItem}`
		let filename = `${sourceName}歌单_${week}_min_${minItem}.xlsx`
		filename = encodeURIComponent(filename)
		let expTask = {
			exp_task_id,
			week,
			filename,
			minItem,
			source,
			sourceName,
			status: 0,
			ips,
		}
		task.exp_list[exp_task_id] = expTask
		task.list = []
		for (let key in task.exp_list) {
			task.list.push(task.exp_list[key])
		}
		await expTaskCol.updateOne({
			_id: task._id,
		}, {
			$set: {
				list: task.list,
				exp_list: task.exp_list,
				modify_time: getTime(),
			}
		})
		let cwd = path.join(__dirname, `../tools`)
		let cmd = `node exportSonglistExcel.js ${source} ${minItem} ${week} > ../../logs/exp_songlist.log 2>&1`
		exec(cmd, {
			cwd
		})
		// fork('exportSonglistExcel.js', [source, minItem], {
		// 	cwd,
		// })
		return new Response('000', '成功')
	},

	weekList: async function(params) {
		let expTaskCol = await _webCrawlerMongo.getCollection('exp_task')
		let docs = await expTaskCol.distinct('week')
		return new Response('000', '成功', {
			total: docs.length,
			docs,
		})
	},

	// exportExcel: async function(params) {
	// 	let {
	// 		source,
	// 		itemNum = 5,
	// 	} = params
	// 	let where = ` (SELECT list_id FROM match_songlist GROUP BY list_id HAVING COUNT(itemid) > ${itemNum}) `
	// 	where += source == 'all' ? '' : ` AND url_source = '${source}' `
	// 	let SQL = 'SELECT url_source, list_id, list_name, tags, profile, itemid, itemname, artist, album, cp, exclusivity FROM match_songlist '
	// 	SQL += ` WHERE list_id in ${where} AND status = 0`
	// 	let docs = await _WebDB.select(SQL)
	// 	let title = ['url_source', 'list_id', 'list_name', 'tags', 'profile', 'itemid', 'itemname', 'artist', 'album', 'cp', 'exclusivity']
	// 	let data = []
	// 	data.push(title)
	// 	for (let i = 0; i < docs.length; i++) {
	// 		let songlist = docs[i]
	// 		let d = []
	// 		for (let j = 0; j < title.length; j++) {
	// 			d.push(songlist[title[j]])
	// 		}
	// 		data.push(d)
	// 	}
	// 	return {
	// 		filename: `${encodeURIComponent('歌单')}_${itemNum}}.xlsx`,
	// 		body: xlsx.build([{
	// 			name: "歌单",
	// 			data
	// 		}]),
	// 	}
	// },

	downloadExcel: async function(params) {
		let {
			week,
			exp_task_id,
		} = params
		let excelDir = path.join(__dirname, `../data/excel/${week}`)
		let expTaskCol = await _webCrawlerMongo.getCollection('exp_task')
		let task = await expTaskCol.findOne({
			task_id: week,
		})
		if (task && task.exp_list && task.exp_list[exp_task_id]) {
			let {
				filename
			} = task.exp_list[exp_task_id]
			return {
				filename,
				body: fs.readFileSync(path.join(excelDir, filename)),
			}
		}
		return {
			filename: encodeURIComponent(`${week}_${exp_task_id || ''}.xlsx`),
			body: xlsx.build([{
				name: "歌单",
				data: [
					['没有数据！']
				]
			}]),
		}
	},

}

/**
 * 密码加密
 * @param  {[type]} password [description]
 * @return {[type]}          [description]
 */
function encPwd(password) {
	return crypto.createHash('md5').update(password).digest('hex');
}